package hydrap2p.upload;

import hydrap2p.ServiceLocation;
import hydrap2p.logging.Level;

import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;

public class UploadProtocols {
	private Map<String, UploadProtocolIface> protocols;
	private UploadQueue queue;
	
	public UploadProtocols()
	{
		protocols=new TreeMap<String, UploadProtocolIface>();
	}
	
	public void setUploadQueue(UploadQueue queue)
	{
		this.queue=queue;
	}
	
	public boolean addUploadProtocol(String name, UploadProtocolIface protocol)
	{
		protocols.put(name, protocol);
		return true;
	}
	
	public boolean removeUploadProtocol(UploadProtocolIface protocol)
	{
		boolean contained=false;
		for (Entry<String, UploadProtocolIface> entry : protocols.entrySet())
		{
			if (entry.getValue().equals(protocol))
			{
				contained=true;
				protocols.remove(entry.getKey());
				if (queue!=null)
					queue.removeProtocolUploads(entry.getKey());
				break;
			}
		}
		return contained;
	}
	
	public boolean removeUploadProtocol(ServiceLocation location)
	{
		for (Entry<String, UploadProtocolIface> entry : protocols.entrySet())
		{
			if (entry.getValue() instanceof UploadProtocolThrift)
			{
				UploadProtocolThrift protocol = (UploadProtocolThrift) entry;
				if (protocol.getLocation().equals(location))
				{
					protocols.remove(entry.getKey());
					return true;
				}
			}
		}
		return false;
	}
	
	public UploadProtocolIface getProtocol(String name)
	{
		return protocols.get(name);
	}
	
	public boolean upload(UploadQueued upload)
	{
		boolean worked=false;
		UploadProtocolIface protocol=protocols.get(upload.protocol);
		if (protocol!=null)
		{
			try
			{
				protocol.upload(upload);
				worked=true;
			}
			catch (Exception e)
			{
				UploadLogging.log(Level.MISHAP, "Upload - Upload Protocols", "An error happened while instructing an Upload Protocol to start an upload, removing from the list");
				removeUploadProtocol(protocol);
			}
		}
		return worked;
	}
	
	public boolean cancelUpload(UploadQueued upload)
	{
		boolean worked=false;
		UploadProtocolIface protocol=protocols.get(upload.protocol);
		if (protocol!=null)
		{
			try
			{
				protocol.cancelUpload(upload);
				worked=true;
			}
			catch (Exception e)
			{
				UploadLogging.log(Level.MISHAP, "Upload - Upload Protocols", "An error happened while instructing an Upload Protocol to start an upload, removing from the list");
				removeUploadProtocol(protocol);
			}
		}
		return worked;
	}
}
